// util.activeMenu    激活menu菜单项目并设定面包屑
// util.loading       Loading Mask
// util.dataTable     封装DataTable
// util.zeroclipboard 封装ZeroClipboard
(function (factory) {
    "use strict";
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(['jquery'], function ($) {
            return factory($, window, document);
        });
    }
    else if (typeof exports === 'object') {
        // CommonJS
        module.exports = function (root, $) {
            if (!root) {
                // CommonJS environments without a window global must pass a
                // root. This will give an error otherwise
                root = window;
            }

            if (!$) {
                $ = typeof window !== 'undefined' ? // jQuery's factory checks for a global window
                    require('jquery') :
                    require('jquery')(root);
            }

            return factory($, root, root.document);
        };
    }
    else {
        // Browser
        factory(jQuery, window, document);
    }
}
(function ($, window, document, undefined) {
    var Util = function () {
        // 激活menu菜单项目并设定面包屑
        var activeMenu = function (actionName) {
            // console.debug('activeMenu: ' + actionName);
            var aObj = $('.main-navigation-menu').find('a[href$="' + actionName + '/"]');
            if ($.Util.isNull(aObj) || aObj.length == 0) aObj = $('.main-navigation-menu').find('a[href$="' + actionName + '"]');
            if ($.Util.isNull(aObj) || aObj.length == 0) aObj = $('.main-navigation-menu').find('a[href$="/' + actionName + '"]');
            if (aObj) {
                // 显示左侧Menu
                aObj.parents('li').addClass('active open');
                // 设定面包屑导航
                $('.breadcrumb').children('li:first').html(aObj.parents('li:last').find('span:first').html());
                $('.breadcrumb').find('a:first').html(aObj.children('span').html());
                $('.breadcrumb').find('a:first').attr('href', '#' + actionName).click(function (e) {
                    e.preventDefault();
                    window.location.reload();
                });
            }
        };
        // animate Css3 动画
        // obj:对象  action:动作类型
        var animate = function (obj, action) {
            var actObj = $('#' + obj) ? actObj = $('#' + obj) : obj;
            actObj.removeClass().addClass(action + ' animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function () {
                $(this).removeClass();
            });
        };
        // ajax Post 提交
        var ajaxPost = function (url, param, options) {
            $.ajaxSetup({
                beforeSend: function (xhr, settings) {
                    if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                        xhr.setRequestHeader("X-CSRFToken", csrf_token)
                    }
                }
            });
            var defaults = {
                url: url,
                param: param,
                async: true,
                showLoading: true,
                lockLoading: false,
                showMsg: true
            };
            var settings = $.extend(defaults, options || {});
            $.ajax({
                type: 'post',
                dataType: 'json',
                async: settings.async,
                url: settings.url,
                data: param,
                success: function (result, status, err) {
                    if (result && settings.showMsg) {
                        if (result.ret_status != null && result.ret_status == 'ok') {
                            if (result.ret_msg != null && result.ret_msg != '') {
                                $.Util.notifySuccess(result.ret_msg);
                            }
                        } else if (result.ret_status != null && result.ret_status == 'info') {
                            if (result.ret_msg != null && result.ret_msg != '') {
                                $.Util.notifyInfo(result.ret_msg);
                            }
                        } else {
                            if (result.ret_msg != null && result.ret_msg != '') {
                                $.Util.notifyWarn(result.ret_msg);
                            }
                        }
                    }
                    if (settings.callback != null) {
                        settings.callback(result, status, err);
                    }
                },
                error: function (result, status, e) {
                    if (result.ret_msg != null && result.ret_msg != '') {
                        $.Util.notifyWarn(result.ret_msg);
                    }
                }
            });
        };
        // 判断空
        var isNull = function (obj) {
            if (obj == null || obj == '') {
                return true;
            } else {
                return typeof(obj) == "undefined";
            }
        };
        // 替换空
        var nvl = function (obj) {
            return isNull(obj) ? '' : obj;
        };
        // 判断是否一致
        var equal = function (obj, aim) {
            if (isNull(obj)) {
                return false;
            } else {
                return obj == aim;
            }
        };
        // loading
        var loading = function (flg) {
            var parentD = $("#loading");
            var loading = $("#loading>div");
            if (flg) {
                //centering function
                jQuery.fn.center = function () {
                    this.css("position", "absolute");
                    this.css("top", (($(window).height() - this.outerHeight()) / 2) + "px");
                    this.css("left", (($(window).width() - this.outerWidth()) / 2) + "px");
                    return this;
                };
                //center to the screen
                parentD.show();
                loading.show();
                loading.center();
                //run each time user resizes window
                $(window).resize(function () {
                    loading.center();
                });
            } else {
                //when the logo and ajax-loader fades out, fade out the curtain; when that completes, remove the universal preloader from the DOM
                loading.delay(200).animate({opacity: '1'}, {
                    duration: 100, complete: function () {
                        parentD.animate({opacity: '1'}, {
                            duration: 100, complete: function () {
                                parentD.hide();
                            }
                        });

                    }
                });
            }
        };
        // 清空Form
        var clearForm = function (form, html) {
            // 清空form
            var inputForm = $('#' + form) ? inputForm = $('#' + form) : form;
            if (html != '') {
                inputForm.html(html);
            }
            $(":input[type='text']", inputForm).val('');
            $(":input[type='checkbox,radio,select']", inputForm).removeAttr('checked').removeAttr('selected');
            //.not(':button, :submit, :reset, :hidden')
            // .not("input[type='hidden,checkbox,radio']")
        };
        // url追加rand
        var randUrl = function (url) {
            if (url != null) {
                url += url.indexOf("?") > 0 ? "&" : "?";
                url += "rand=" + Math.random();
            }
            return url;
        };
        // 重新刷新页面
        var reload = function (url) {
            window.location.href = randUrl(url);
        };
        // 封装提示
        var pnotifyExc = function (msg, titleMsg, type) {
            require(['jquery', 'pnotify', 'pnotify.nonblock', 'pnotify.desktop', 'pnotify.buttons'], function ($, PNotify) {
                var title = titleMsg ? titleMsg : '信息提示';
                PNotify.desktop.permission();
                new PNotify({
                    type: type,
                    title: title,
                    text: msg,
                    opacity: 0.92,
                    delay: 3000,
                    hide: true,
                    history: false,
                    desktop: {
                        desktop: true
                    },
                    buttons: {
                        sticker: false,
                        closer: true
                    }
                });
            });
        };
        // 设定更新和新增按钮样式和内容 add:新增 update:编辑
        var setSumbitBtn = function (type, obj) {
            var object = {};
            var btnId = (obj && obj != '') ? obj : 'submitBtn';
            var btn = $('.' + btnId) ? $('.' + btnId) : btnId;
            if (type == 'add') {
                btn.removeClass('btn-green').addClass('btn-yellow');
                btn.find('span:first').html(_Btn_Add_);
            } else {
                $(btn).removeClass('btn-yellow').addClass('btn-green');
                btn.find('span:first').html(_Btn_Update_);
            }
        };
        // 根据name读取form内容生成对象
        var getFormData = function (form) {
            var object = {};
            var inputForm = $('#' + form) ? $('#' + form) : form;
            $.each(inputForm.serializeArray(), function (index) {
                var name = this['name'] + '';
                var value = this['value'] + '';
                if (object[name]) {
                    object[name] += ',' + $.trim(value);
                } else {
                    object[name] = $.trim(value);
                }
                // console.debug(name +' : '+ object[name]);
            });
            return object;
        };
        // 取得DataTable 封装更新按钮
        var getEditBtn = function (data, type, row) {
            var retHtml = "";
            if (!$.Util.isNull(row[0])) {
                var editBtn = $('<a/>', {
                    'class': 'btn btn-xs btn-blue tooltips updateBtn',
                    'data-id': row[0],
                    'data-placement': 'bottom',
                    'data-original-title': '编辑'
                }).append($('<i/>', {
                    'class': 'fa fa-edit'
                }));
                retHtml = editBtn.prop("outerHTML");
            }
            return retHtml;
        };
        // 取得DataTable 封装删除按钮
        var getDelBtn = function (data, type, row) {
            var retHtml = "";
            if (!$.Util.isNull(row[0])) {
                var delBtn = $('<a/>', {
                    'class': 'btn btn-xs btn-red tooltips delBtn',
                    'data-id': row[0],
                    'data-placement': 'bottom',
                    'data-original-title': '删除',
                }).append($('<i/>', {
                    'class': 'fa fa-times'
                }));
                retHtml = delBtn.prop("outerHTML");
            }
            return retHtml
        };
        /*
         * 给按钮绑定复制功能
         * btn 绑定的按钮
         * callback 回调方法
         * */
        var zeroClipboard = function (btn, ZeroClipboard, callback) {
            var client = new ZeroClipboard(btn);
            client.on("ready", function (event) {
                // alert( "ZeroClipboard SWF is ready!" );
                client.on('copy', function (event) {
                    if (callback) {
                        event.clipboardData.setData('text/plain', callback());
                    }
                });
                client.on('aftercopy', function (event) {
                    $.Util.notifySuccess("已将结果复制到粘帖板");
                    try {
                        setTimeout(function () {
                            btn.blur();
                        }, 500);
                    } catch (e) {
                    }
                });
            });
            client.on('error', function (event) {
                ZeroClipboard.destroy();
            });
        };
        return {
            activeMenu: function (actionName) {
                return activeMenu(actionName);
            },
            ajaxPost: function (url, param, options) {
                return ajaxPost(url, param, options);
            },
            animate: function (obj, action) {
                return animate(obj, action);
            },
            clearForm: function (form, html) {
                return clearForm(form, html);
            },
            dataTable: function (options) {
                require(['jquery', 'util-datatable'], function ($) {
                    try {
                        return $.datatable.init(options);
                    } catch (err) {
                    }
                });
            },
            equal: function (obj, aim) {
                return equal(obj, aim);
            },
            reloadDataTable: function (options) {
                require(['jquery', 'util-datatable'], function ($) {
                    return $.datatable.reloadTable(options.id);
                });
            },
            getEditBtn: function (data, type, row) {
                return getEditBtn(data, type, row);
            },
            getDelBtn: function (data, type, row) {
                return getDelBtn(data, type, row);
            },
            getFormData: function (form) {
                return getFormData(form);
            },
            getTableSelectId: function (tableId, column, key) {
                return $.datatable.getTableSelectId(tableId, column, key);
            },
            isNull: function (obj) {
                return isNull(obj);
            },
            nvl: function (obj) {
                return nvl(obj);
            },
            randUrl: function (url) {
                return randUrl(url);
            },
            reload: function (url) {
                return reload(url);
            },
            loading: function (flg) {
                return loading(flg);
            },
            notifyWarn: function (msg, title) {
                return pnotifyExc(msg, title, "error");
            },
            notifySuccess: function (msg, title) {
                return pnotifyExc(msg, title, "success");
            },
            notifyInfo: function (msg, title) {
                return pnotifyExc(msg, title, "info");
            },
            setSumbitBtn: function (type, obj) {
                return setSumbitBtn(type, obj);
            },
            zeroClipboard: function (btn, callback) {
                require(['jquery', 'ZeroClipboard'], function ($, ZeroClipboard) {
                    return zeroClipboard(btn, ZeroClipboard, callback);
                });
            }
        };
    }(jQuery);
    // jQuery access
    $.Util = Util;
}));